// pages/user/register/register.js
var app=getApp();
var countdown = 120;
var reget = '获取验证码';
var timer;
var isTimer = false;//timer是否开始
// 定时器
var settime = function (that) {
  if (countdown == 0) {
    that.setData({
      is_show: true,
    })
    countdown = 120;
    reget = '重新获取';
    isTimer = false;
    return;
  } else {
    that.setData({
      is_show: false,
      last_time: countdown
    })
    isTimer = true;
    countdown--;
    reget = '重新获取';
  }
  timer = setTimeout(function () {
    settime(that)
  }
    , 1000)
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',//手机号码
    simcode:'',//验证码
    getOnecode: reget,//内容
    last_time: '',//剩余时间
    is_show: true,//是否显示倒计时
  },


  /**
     * 生命周期函数--监听页面加载
     */
  onLoad: function (options) {
    var that = this;
    if (options.type && (options.type == 'register')){
      wx.setNavigationBarTitle({
        title: '注册',
      })
    }else{
      wx.setNavigationBarTitle({
        title: '短信登录',
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 清除timer
    clearTimeout(timer);
    isTimer = false;

  },
  //手机号码输入
  phoneinput(e){
    var that=this;
    that.setData({
      phone: e.detail.value
    })
  },
  //输入验证码
  inputCode(e){
    var that = this;
    that.setData({
      simcode: e.detail.value
    })
  },
  //获取验证码
  getCode() {
    var that=this;
    console.log('isTimer:' + isTimer);
    if (isTimer){
      console.log('timer已经开始');
      return;
    }
    var phone_num = that.data.phone;
    var numreg = /^[1][3-9][\d]{9}$/;
    if (phone_num==''){
      app.showToast("手机号码不能为空", "none", 2000, function () { });
      return false;
    }
    if (numreg.test(phone_num)==false){
      app.showToast("请输入正确手机的号码", "none", 2000, function () { });
      return false;
    }
    isTimer = true;
    app.ajax({
      url: "Common/Common/sendSms",
      data: { tel: phone_num},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            is_show: (!that.data.is_show)  //false
          })
          countdown = 120;
          reget = '获取验证码'; 
          settime(that); //刷新倒计时 
          that.setData({
            getOnecode: reget
          })
          app.showToast(res.data.message, "none", 4000, function () { });
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
      }
    })
  },
  //提交
  present(){
    var that=this;
    var phone_num = that.data.phone;
    var simcode = that.data.simcode;
    if (phone_num == '') {
      app.showToast("手机号码不能为空", "none", 2000, function () { });
      return false;
    } else if (simcode==''){
      app.showToast("验证码不能为空", "none", 2000, function () { });
      return false;
    }
    wx.setStorageSync('phone', phone_num);
    app.bindGetnewToken(1, simcode,2);
  }
})